#include "StdAfx.h"
#include "TimeCounter.h"

#include <windows.h>

void TimeCounter::Start()
{
   started=true;
   stopped=false;
   new_priority=0;

   LARGE_INTEGER pf;
    QueryPerformanceFrequency(&pf);
   i64PerfFrequency = pf.QuadPart;
    Sleep(0);
    QueryPerformanceCounter(&pf);
   tBefore = pf.QuadPart;
}

void TimeCounter::Start(int nPriority)
{
   started=true;
   stopped=false;
   new_priority=nPriority;
   old_priority=GetThreadPriority(GetCurrentThread());
   SetThreadPriority(GetCurrentThread(),new_priority);

   LARGE_INTEGER pf;
    QueryPerformanceFrequency(&pf);
   i64PerfFrequency = pf.QuadPart;
    Sleep(0); 
   QueryPerformanceCounter(&pf);
   tBefore = pf.QuadPart;
}

void TimeCounter::Stop()
{
   LARGE_INTEGER tAfter1;
   QueryPerformanceCounter(&tAfter1);
   tAfter = tAfter1.QuadPart;

   tWord = tAfter - tBefore;
   tWord /= i64PerfFrequency;
   if (new_priority)
      SetThreadPriority(GetCurrentThread(),old_priority);
   started=false;
   stopped=true;
}
   
double TimeCounter::timeElapsed() const
{
   LARGE_INTEGER tempAfter;
   double tempWord;

   if (started)
   {
      QueryPerformanceCounter(&tempAfter);
      tempWord = tempAfter.QuadPart - tBefore;
      tempWord /= i64PerfFrequency;

      return tempWord;
   }
   if (stopped)
      return tWord;
   
   return 0.;
}

TimeCounter::~TimeCounter()
{
   if (new_priority)
      SetThreadPriority(GetCurrentThread(),old_priority);
}

std::ostream& operator<<(std::ostream& out, TimeCounter& cntr)
{
   double fsec = cntr.timeElapsed();
   int hour = int(fsec/3600.);
   double fmin = fsec-3600.*double(hour);
   int min = int(fmin/60.);
   double sec = fmin-60.*double(min);
   out<<"Time elapsed: "<<hour<<" h. "<<min<<" min. "<<sec<<" sec."<<std::endl;
   return out;
}
